<?php

namespace app\admin\service;

use support\spark\exception\ApiException;
use  support\spark\model\goods\Goods;
use  support\spark\model\goods\GoodsRule;
use  support\spark\model\goods\GoodsRuleExtend;
use  support\spark\model\goods\GoodsRuleTpl;

class GoodsRuleService
{


    /**
     * 获取商品列表
     * @param $param
     * @return array
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $name = $param['name'];

        $where = [];
        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $goodsRuleModel = new GoodsRuleTpl();
        $list = $goodsRuleModel->getPaginateList($where, ['*'], ['id' => 'desc'], [], $limit);

        foreach ($list['data'] as $key => $item) {
            $data = json_decode($item['value'], true);
            $title = '';
            $items = '';
            foreach ($data as $vo) {
                $title .= $vo['title'] . ',';
                $items .= implode(',', $vo['item']) . ' | ';
            }
            $list['data'][$key]['title'] = rtrim($title, ',');
            $list['data'][$key]['item'] = rtrim($items, '|');
        }
        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加商品规格
     * @param $param
     * @return array
     */
    public function addGoodsRule($param)
    {
        $name = $param['name'];
        unset($param['name'], $param['id']);

        $goodsRuleModel = new GoodsRuleTpl();
        $has = $goodsRuleModel->checkUnique([
            'name' => $name
        ]);
        if (!empty($has)) {
            throw new  ApiException('该模板名称已经存在');
        }
        // 检测数据的合法性
        $value = [];
        $uniqueItemName = [];
        foreach ($param as $vo) {
            if (isset($uniqueItemName[$vo['title']])) {
                throw new  ApiException('规则名' . $vo['title'] . '已经存在');
            }
            if (!isset($vo['item'])) {
                throw new  ApiException('规则名' . $vo['title'] . '的规则值缺失，请补充');
            }

            $uniqueItemName[$vo['title']] = 1;
            $itemsLen = count($vo['item']);
            if ($itemsLen > array_unique($vo['item'])) {
                throw new  ApiException('规则名' . $vo['title'] . '的规则值重复，请认真检查');
            }
            $value[] = $vo;
        }

        $addParam['name'] = $name;
        $addParam['value'] = json_encode($value);
        $addParam['create_time'] = now();
        $addParam['update_time'] = now();
        $goodsRuleModel->insertOne($addParam);
        return   dataReturn(0,'添加成功');
    }


    /**
     * 编辑商品规则
     * @param $param
     * @return array
     */
    public function editGoodsRule($param)
    {
        $id = $param['id'];
        $name = $param['name'];
        unset($param['name'], $param['id']);

        $goodsRuleModel = new GoodsRuleTpl();

        $where[] = ['id', '<>', $id];
        $where[] = ['name', '=', $name];
        $has = $goodsRuleModel->checkUnique($where);
        if (!empty($has)) {
            throw new  ApiException('规则名已经存在');
        }
        // 检测数据的合法性
        $value = [];
        $uniqueItemName = [];
        foreach ($param as $vo) {

            if (isset($uniqueItemName[$vo['title']])) {
                throw new  ApiException('规则名' . $vo['title'] . '已经存在');
            }

            if (!isset($vo['item'])) {
                throw new  ApiException('规则名' . $vo['title'] . '的规则值缺失，请补充');
            }

            $uniqueItemName[$vo['title']] = 1;
            $itemsLen = count($vo['item']);
            if ($itemsLen > array_unique($vo['item'])) {
                throw new  ApiException('规则名' . $vo['title'] . '的规则值重复，请认真检查');
            }

            $value[] = $vo;
        }

        $editParam['name'] = $name;
        $editParam['value'] = json_encode($value);
        $goodsRuleModel->updateById($editParam, $id);
        return   dataReturn(0,'修改成功');
    }


    /**
     * 根据商品id获取规格
     * @param $goodsId
     * @return array
     */
    public function getRuleByGoodsId($goodsId)
    {
        $goodsRuleModel = new GoodsRule();
        $goodsRuleExtendModel = new GoodsRuleExtend();
        $goodsModel = new Goods();

        return dataReturn(0, 'success', [
            'ruleData' => $goodsRuleModel->getInfoByWhere([
                    'goods_id' => $goodsId
                ]) ?? '{}',
            'goods_info' => $goodsModel->getInfoByWhere([
                'id' => $goodsId
            ], ['stock']),
            'extend' => $goodsRuleExtendModel->getAllList([
                    'goods_id' => $goodsId
                ], ['*'], ['id' => 'asc']) ?? '{}'
        ]);
    }
}
